package com.cooperate.fly.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cooperate.fly.bo.BaseNode;
import com.cooperate.fly.bo.Case;
import com.cooperate.fly.bo.DataRight;
import com.cooperate.fly.bo.Schema;
import com.cooperate.fly.bo.User;
import com.cooperate.fly.bo.UserGroup;
import com.cooperate.fly.mapper.CaseMapper;
import com.cooperate.fly.mapper.DataRightMapper;
import com.cooperate.fly.mapper.SchemaMapper;
import com.cooperate.fly.mapper.UserGroupMapper;
import com.cooperate.fly.mapper.UserMapper;
import com.cooperate.fly.service.buildDB.BuildCaseService;
import com.cooperate.fly.service.buildDB.BuildSchemaService;
import com.cooperate.fly.service.system.Constant;
import com.cooperate.fly.service.system.UserGroupService;
import com.cooperate.fly.service.system.UserService;
import com.cooperate.fly.web.BaseTreeNode;
import com.cooperate.fly.web.Result;
import com.cooperate.fly.web.TypeTreeNode;
import com.cooperate.fly.web.UserNode;
import com.cooperate.fly.web.WebFrontHelper;
import com.google.gson.Gson;

@Controller
public class LoginController {

	private static Logger log = Logger.getLogger(LoginController.class);
	@Resource
	private UserService userService;
	@Resource
	private BuildSchemaService buildSchemaService;
	@Resource
	private BuildCaseService buildCaseService;
	@Resource
	private UserMapper usermapper;
	@Resource
	private DataRightMapper dataRightMapper;
	@Resource
	private UserGroupService userGroupService;
	@Resource
	private UserGroupMapper userGroupMapper;
	@Resource
	private SchemaMapper schemaMapper;
	@Resource
	private CaseMapper caseMapper;

	@Resource
	private WebFrontHelper webFrontHelper;

	@Value("#{propertiesReader['schema_designer_role_id']}")
	public int schemaDesignerRoleId;
	@Value("#{propertiesReader['case_designer_role_id']}")
	public int caseDesignerRoleId;
	@Value("#{propertiesReader['root_role_id']}")
	public int rootRoleId;
	@Value("#{propertiesReader['dWriteAuth']}")
	public int writeAuth;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage(HttpSession session, Model model) {
		// 保存session为了用户关闭页面之后能够自动登录
		User user = (User) session.getAttribute(Constant.USER_SESSION_KEY);
		if (user == null) {
			return "login";
		}

		int roleId = user.getRoleId();
		if (roleId == schemaDesignerRoleId) {
			String temp = buildSchemaService.loadSchema();
			model.addAttribute("schemaData", temp);
			return "schema-design";
		} else if (roleId == caseDesignerRoleId) {
			List<Schema> schemas = new ArrayList<Schema>();
			List<Case> cases = new ArrayList<Case>();
			List<DataRight> rights = dataRightMapper.selectByUserId(
					user.getId(), writeAuth);
			Set<Schema> schemaParent = new HashSet<Schema>();
			for (DataRight right : rights) {
				int schemaId = right.getSchemaid();
				Schema schema = schemaMapper.selectByPrimaryKey(schemaId);
				schemas.add(schema);
				Schema parent = schemaMapper.selectByPrimaryKey(schema
						.getParentId());
				if (parent != null) {
					schemaParent.add(parent);
					Queue<Schema> queue = new LinkedList<Schema>();
					queue.offer(parent);
					while (!queue.isEmpty()) {
						Schema p = schemaMapper.selectByPrimaryKey(queue.poll()
								.getParentId());
						if (p != null) {
							schemaParent.add(p);
							queue.offer(p);
						}
					}
				}
				List<Case> schema_cases = caseMapper
						.selectAllBySchemaId(schemaId);
				cases.addAll(schema_cases);
			}
			for (Schema schema_parent : schemaParent) {
				schemas.add(schema_parent);
			}
			// List<Schema> schemas = schemaMapper.selectAll();
			// List<Case> cases = buildCaseService.getAllCases();
			List<BaseNode> schemaAndCases = new ArrayList<BaseNode>();
			schemaAndCases.addAll(schemas);
			for (Case _case : cases) {
				schemaAndCases.add(_case);
			}
			BaseTreeNode root = webFrontHelper.buildCaseTree(schemaAndCases,
					null);
			List<BaseTreeNode> list = new ArrayList<BaseTreeNode>();
			list.add(root);
			String temp = new Gson().toJson(list);
			model.addAttribute("caseData", temp);
			return "case-design";
		} else if (roleId == rootRoleId) {
			List<User> userList = userService.findAll();
			List<UserNode> userNodes = WebFrontHelper.buildUserGrid(userList,
					userGroupMapper);
			model.addAttribute("userJson", new Gson().toJson(userNodes));
			ArrayList<UserGroup> groups = userGroupService.findAll();
			TypeTreeNode groupRoot = webFrontHelper.buildGroupTree(groups);
			model.addAttribute("groupTreeJson",
					new Gson().toJson(groupRoot.getChildren()));
			model.addAttribute("groupJson", new Gson().toJson(groups));
			return "user-design";
		}
		return "grant-tips";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public String login(
			@RequestParam(value = "userName", required = true) String userName,
			@RequestParam(value = "password", required = true) String password,
			HttpSession session) {
		User user = this.userService.loadUserByUserNameAndPassword(userName,password);
		
		Gson gson = new Gson();
		if (user != null) {
			log.info("登录成功：{}" + user);
			session.setAttribute(Constant.USER_SESSION_KEY, user);
			return gson.toJson(new Result());
		} else {
			return gson.toJson(new Result("用户名密码不匹配"));
		}
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		if (session != null) {
			session.invalidate();
		}
		return "redirect:/";
	}

	@RequestMapping("checkSession")
	@ResponseBody
	public String checkSession(HttpSession session) {
		Gson gson = new Gson();
		
		if (session.getAttribute(Constant.USER_SESSION_KEY) != null) {
			return gson.toJson(new Result());
		}
		return gson.toJson(new Result(false));
	}
}
